//
//  JWTForgetPWDViewController.m
//  JWT
//
//  Created by ndm on 17/2/3.
//  Copyright © 2017年 com.jwtsoft. All rights reserved.
//

#import "JWTForgetPWDViewController.h"
#import "JWTLoginViewController.h"
#import "NSTimerBlock.h"
#import "JWTTextField.h"


@interface JWTForgetPWDViewController ()<UITextFieldDelegate>

@property (nonatomic,strong) JWTTextField *phoneForgetField;
@property (nonatomic,strong) UIButton *sendVercodeButton;
@property (nonatomic,strong) JWTTextField *checkVercodeFiled;
@property (nonatomic,strong) JWTTextField *setNewPWDFiled;
@property (nonatomic,strong) JWTTextField *confNewPWDeFiled;

@property (nonatomic,strong) UIButton *changePassWordBtn;
@property (nonatomic,strong) UIButton *nextStepBtn;

@end
@implementation JWTForgetPWDViewController

-(instancetype)init{
    if ([super init]) {
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initWithNavTitle:@"忘记密码"];
    
    [self layoutView];
}
/**
  初始化视图
 */
-(void) layoutView{
    CGFloat margin = Cell_Margin;
    //手机号码hint
    _phoneForgetField = [[JWTTextField alloc] initWithFrame:CGRectMake(2*margin, 4*margin, UISCREEN_WIDTH-4*Cell_Margin-(UISCREEN_WIDTH- 20)/3, 50)];
    _phoneForgetField.layer.borderWidth = 0.5f;
    _phoneForgetField.layer.cornerRadius = _phoneForgetField.height * 0.5;
    _phoneForgetField.layer.borderColor = RGB_LightGray.CGColor;
    _phoneForgetField.clearButtonMode = UITextFieldViewModeAlways;
    _phoneForgetField.delegate = self;
    _phoneForgetField.placeholder = @"请输入手机号";
    [self.view addSubview:_phoneForgetField];
    
    UIImageView *rephoneImageView = [[UIImageView alloc] initWithFrame:CGRectMake(margin, 8, 34, 34)];
    [rephoneImageView setImage:[UIImage imageNamed:@"Phone"]];
    rephoneImageView.contentMode = UIViewContentModeScaleAspectFit;
    rephoneImageView.layer.masksToBounds = YES;
    _phoneForgetField.leftViewMode=UITextFieldViewModeAlways;
    _phoneForgetField.leftView.frame = CGRectMake(margin, 8, 34, 34);
    _phoneForgetField.leftView = rephoneImageView;

    //发送验证码
    _sendVercodeButton = [[UIButton alloc]initWithFrame:CGRectMake(_phoneForgetField.right+margin, _phoneForgetField.top, (UISCREEN_WIDTH- 20)/3, _phoneForgetField.height-12)];
    [_sendVercodeButton setTitle:@"发送验证码" forState:UIControlStateNormal];
    [_sendVercodeButton setBackgroundColor:HeaderBackground_Color];
    [_sendVercodeButton setTitleColor:RGB_WhiteBackGround forState:UIControlStateNormal];
    _sendVercodeButton.layer.cornerRadius = _sendVercodeButton.height*0.5;
//    _sendVercodeButton.layer.borderWidth = 0.5;
    _sendVercodeButton.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
    [_sendVercodeButton addTarget:self action:@selector(senderVercodeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_sendVercodeButton];
    _sendVercodeButton.center = CGPointMake(_sendVercodeButton.center.x, _phoneForgetField.center.y);
    
    //验证码
    _checkVercodeFiled = [[JWTTextField alloc] initWithFrame:CGRectMake(_phoneForgetField.left, _phoneForgetField.bottom+Cell_Margin,UISCREEN_WIDTH-2*_phoneForgetField.left, 50)];
    _checkVercodeFiled.layer.borderWidth = 0.5f;
    _checkVercodeFiled.layer.cornerRadius = _checkVercodeFiled.height * 0.5;
    _checkVercodeFiled.layer.borderColor = RGB_LightGray.CGColor;
    _checkVercodeFiled.placeholder = @"请输入验证码";
    _checkVercodeFiled.delegate = self;
    _checkVercodeFiled.clearButtonMode = UITextFieldViewModeAlways;
    [self.view addSubview:_checkVercodeFiled];
    
    UIImageView *resVerifyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(Cell_Margin, 8, 30, 30)];
    [resVerifyImageView setImage:[UIImage imageNamed:@"VerifyCode"]];
    resVerifyImageView.contentMode = UIViewContentModeScaleAspectFit;
    resVerifyImageView.layer.masksToBounds = YES;
    _checkVercodeFiled.leftViewMode=UITextFieldViewModeAlways;
    _checkVercodeFiled.leftView.frame = CGRectMake(Cell_Margin, 8, 34, 34);
    _checkVercodeFiled.leftView = resVerifyImageView;
    
    
//    //新密码
    _setNewPWDFiled = [[JWTTextField alloc] initWithFrame:CGRectMake(_checkVercodeFiled.left, _checkVercodeFiled.bottom+Cell_Margin, _checkVercodeFiled.width, 50)];
    _setNewPWDFiled.layer.borderWidth = 0.5f;
    _setNewPWDFiled.layer.cornerRadius = _setNewPWDFiled.height * 0.5;
    _setNewPWDFiled.layer.borderColor = RGB_LightGray.CGColor;
    _setNewPWDFiled.placeholder = @"请设置新密码";
    _setNewPWDFiled.secureTextEntry = YES;
    _setNewPWDFiled.delegate = self;
    _setNewPWDFiled.clearButtonMode = UITextFieldViewModeAlways;
    [self.view addSubview:_setNewPWDFiled];
    
    UIImageView *resPassWordImageView = [[UIImageView alloc] initWithFrame:CGRectMake(Cell_Margin, 8, 30, 30)];
    [resPassWordImageView setImage:[UIImage imageNamed:@"PassWord"]];
    resPassWordImageView.contentMode = UIViewContentModeScaleAspectFit;
    resPassWordImageView.layer.masksToBounds = YES;
    _setNewPWDFiled.leftViewMode=UITextFieldViewModeAlways;
    _setNewPWDFiled.leftView.frame = CGRectMake(Cell_Margin, 8, 34, 34);
    _setNewPWDFiled.leftView = resPassWordImageView;
    
    _confNewPWDeFiled = [[JWTTextField alloc] initWithFrame:CGRectMake(_setNewPWDFiled.left, _setNewPWDFiled.bottom+Cell_Margin, _setNewPWDFiled.width, 50)];
    _confNewPWDeFiled.layer.borderWidth = 0.5f;
    _confNewPWDeFiled.layer.cornerRadius = _setNewPWDFiled.height * 0.5;
    _confNewPWDeFiled.layer.borderColor = RGB_LightGray.CGColor;
    _confNewPWDeFiled.placeholder = @"请确认新密码";
    _confNewPWDeFiled.secureTextEntry = YES;
    _confNewPWDeFiled.delegate = self;
    _confNewPWDeFiled.clearButtonMode = UITextFieldViewModeAlways;
    [self.view addSubview:_confNewPWDeFiled];
    
    UIImageView *confPassWordImageView = [[UIImageView alloc] initWithFrame:CGRectMake(Cell_Margin, 8, 30, 30)];
    [confPassWordImageView setImage:[UIImage imageNamed:@"PassWord"]];
    confPassWordImageView.contentMode = UIViewContentModeScaleAspectFit;
    confPassWordImageView.layer.masksToBounds = YES;
    _confNewPWDeFiled.leftViewMode=UITextFieldViewModeAlways;
    _confNewPWDeFiled.leftView.frame = CGRectMake(Cell_Margin, 8, 34, 34);
    _confNewPWDeFiled.leftView = confPassWordImageView;
    
//    //注册
    _nextStepBtn = [[UIButton alloc] initWithFrame:CGRectMake(UISCREEN_WIDTH*0.25, _confNewPWDeFiled.bottom+margin*2, UISCREEN_WIDTH*0.5, 50)];
    _nextStepBtn.layer.borderWidth = 0.5f;
    _nextStepBtn.layer.cornerRadius = _nextStepBtn.height * 0.5;
    _nextStepBtn.layer.borderColor = RGB_LightGray.CGColor;
    [_nextStepBtn setTitle:@"确认修改" forState:UIControlStateNormal];
    [_nextStepBtn setTitleColor:RGB_WhiteBackGround forState:UIControlStateNormal];
    [_nextStepBtn setBackgroundColor:HeaderBackground_Color];
    [self.view addSubview:_nextStepBtn];
    
    WS(weakSelf);
    [_nextStepBtn addButtonBlockControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [weakSelf forgetPWDCommit];
    }];

}

//获取短信验证码
-(void) senderVercodeAction:(UIButton *)sender{
    //1.手机号不能为空
    if ([_phoneForgetField.text isEqualToString:@""]) {
        [HUD showToast:@"请输入手机号"];
        return;
        
    }else if ([[JWTCommons sharedInstance] validateMobile:_phoneForgetField.text] == 0){
        [HUD showToast:@"手机号格式不正确"];
        return;
    }else{
        [_phoneForgetField resignFirstResponder];
        //点击按钮获取验证码接口
        NSString *urlString = [[JWTAPPHttpsUrl sharedInstance] getVerifyCodeWithActionRegisterWithTel:_phoneForgetField.text andType:@"1"];
        [AFNHttpsRequest requestWithUrl:urlString WithParam:nil WithGetDataDidFinishBlock:^(id model, NSURLSessionDataTask *task, NSError *error) {
            [HUD hideUIBlockingIndicator];
            NSLog(@"%@",model);
            if (model) {
                //code：200-请求成功，0-请求失败，400-非法ip访问，406-手机格式不正确，4030-手机号被列入黑名单，1-（type=0，用户已注册；type=1，用户不存在
                if ([[model objectForKey:@"code"] integerValue] == 200) {
                    [HUD showToast:GetVerifyCode_Success];
                    //创建定时器计时
                    ((UIButton *)sender).enabled = NO;
                    __block NSInteger timersec = 60;
                    __block NSTimerBlock *timer = [NSTimerBlock scheduledTimerWithTimeInterval:1.0 scheduledBlock:^(NSTimerBlock *aTimer)
                                                   {
                                                       timersec--;
                                                       NSLog(@"timersec=%ld",(long)timersec);
                                                       if(timersec <=0)
                                                       {
                                                           ((UIButton *)sender).enabled = YES;
                                                           [timer invalidate];
                                                       }
                                                       else
                                                       {
                                                           [((UIButton *)sender) setTitle:[NSString stringWithFormat:@"%ld秒",timersec] forState:UIControlStateDisabled];
                                                       }
                                                       
                                                   }];
                }else{
                    [HUD showToast:[model objectForKey:@"message"]];
                }
            }
        }];
    }
}

/**
 忘记密码
 */
-(void) forgetPWDCommit{
    if ([_phoneForgetField.text isEqualToString:@""]||[_checkVercodeFiled.text isEqualToString:@""]||[_setNewPWDFiled.text isEqualToString:@""]||[_confNewPWDeFiled.text isEqualToString:@""]) {
        [HUD showToast:@"信息不完整"];
        return;
    }else{
        if ([[JWTCommons sharedInstance] validateMobile:_phoneForgetField.text] == 0){
            [HUD showToast:@"手机号格式不正确"];
            return;
        }else if ([_setNewPWDFiled.text length]<6 || [_confNewPWDeFiled.text length]<6){
            [HUD showToast:@"密码不能小于6位"];
            return;
        }else if (![_setNewPWDFiled.text isEqualToString:_confNewPWDeFiled.text]){
            [HUD showToast:@"两次密码输入不一致"];
            return;
        }
    }
    
    [HUD showUIBlockingIndicator];
    NSString *urlString = [[JWTAPPHttpsUrl sharedInstance] updateForgetPasswordWithActionUpdateForgetPassword];
    
    NSDictionary *dict = @{@"tel":_phoneForgetField.text,@"password":[NSString md5:_setNewPWDFiled.text],@"telcode":_checkVercodeFiled.text};
    
    [AFNHttpsRequest requestWithUrl:urlString WithParam:dict WithGetDataDidFinishBlock:^(id model, NSURLSessionDataTask *task, NSError *error) {
        [HUD hideUIBlockingIndicator];
        [self resignFirstResponseAction];
        if (model) {
            if ([[model objectForKey:@"code"] integerValue] == 200) {
                NSLog(@"%@",model);
                [HUD showToast:@"找回密码成功"];
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:_phoneForgetField.text forKey:@"tel"];
                [userDefaults setObject:@"" forKey:@"userName"];
                [userDefaults setObject:@"" forKey:@"passWord"];
                [userDefaults setObject:@"" forKey:@"tokenID"];
                [userDefaults synchronize];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"Add_UserPhoneTextAction" object:nil];
                [self.navigationController popViewControllerAnimated:YES];
                
            }else if([[model objectForKey:@"code"] integerValue] == 260){
                [HUD showToast:@"验证码错误"];
            }else{
                [HUD showToast:@"修改失败"];
            }
        }
    }];
}

/**
 取消第一响应者
 */
-(void) resignFirstResponseAction{
    [_setNewPWDFiled resignFirstResponder];
    [_confNewPWDeFiled resignFirstResponder];
    [_phoneForgetField resignFirstResponder];
    [_checkVercodeFiled resignFirstResponder];
}

@end
